﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
using Tridion.ContentManager.CoreService.Client;
using TridionDesktopTools.Core;

namespace TridionDesktopTools.IntegrityAnalyzer
{
    public partial class MainWindow
    {
        public TridionObjectInfo TridionObject { get; set; }
        public TridionSelectorMode TridionSelectorMode { get; set; }

        public MainWindow()
        {
            InitializeComponent();

            this.cbBindingType.ItemsSource = Enum.GetNames(typeof(BindingType));
            this.cbBindingType.Text = Functions.GetFromIsolatedStorage("BindingType");
            if (String.IsNullOrEmpty(this.cbBindingType.Text))
                this.cbBindingType.SelectedIndex = 0;
            
            //get from isolated stoage
            this.txtHost.Text = Functions.GetFromIsolatedStorage("Host");
            this.txtUsername.Text = Functions.GetFromIsolatedStorage("Username");
            this.txtPassword.Password = Functions.GetFromIsolatedStorage("Password");

            this.TridionSelectorMode = TridionSelectorMode.FolderAndSchema;
            this.lblTridionObject.Content = "Select Publication\n or Folder\n or Schema";
        }

        private void btnConnect_Click(object sender, RoutedEventArgs e)
        {
            Functions.ResetClient();

            Functions.ClientBindingType = (BindingType)Enum.Parse(typeof(BindingType), this.cbBindingType.Text);
            Functions.SaveToIsolatedStorage("BindingType", this.cbBindingType.Text);

            if (!Functions.EnsureValidClient(this.txtHost.Text, this.txtUsername.Text, this.txtPassword.Password))
                return;

            this.lblTridionObject.Visibility = Visibility.Visible;
            this.treeTridionObject.Visibility = Visibility.Visible;
            
            this.TridionObject = new TridionObjectInfo();
            
            string containerTcmId = Functions.GetFromIsolatedStorage(this.txtHost.Text + "_ContainerTcmId");
            if (!String.IsNullOrEmpty(containerTcmId))
            {
                this.TridionObject.TcmId = containerTcmId;
            }

            string strContainerTcmIdPath = Functions.GetFromIsolatedStorage(this.txtHost.Text + "_ContainerTcmIdPath");
            if (!String.IsNullOrEmpty(strContainerTcmIdPath))
            {
                this.TridionObject.TcmIdPath = strContainerTcmIdPath.Split(';').ToList();
            }

            List<ItemInfo> publications = Functions.GetPublications(this.txtHost.Text, this.txtUsername.Text, this.txtPassword.Password).Expand(this.txtHost.Text, this.txtUsername.Text, this.txtPassword.Password, TridionSelectorMode, this.TridionObject.TcmIdPath, this.TridionObject.TcmId).MakeExpandable();
            this.treeTridionObject.ItemsSource = publications;

            if (publications != null && publications.Count > 0)
            {
                //save to isolated stoage
                Functions.SaveToIsolatedStorage("Host", this.txtHost.Text);
                Functions.SaveToIsolatedStorage("Username", this.txtUsername.Text);
                Functions.SaveToIsolatedStorage("Password", this.txtPassword.Password);
            }
        }

        private void TreeViewItem_Expanded(object sender, RoutedEventArgs e)
        {
            ItemInfo item = ((TreeViewItem)e.OriginalSource).DataContext as ItemInfo;
            if (item == null)
                return;

            Functions.OnItemExpanded(this.txtHost.Text, this.txtUsername.Text, this.txtPassword.Password, item, this.TridionSelectorMode);
        }

        private void TreeViewItem_Selected(object sender, RoutedEventArgs e)
        {
            ItemInfo item = ((TreeViewItem)e.OriginalSource).DataContext as ItemInfo;
            if (item == null)
                return;

            this.TridionObject.TcmId = item.TcmId;

            Functions.SaveToIsolatedStorage(this.txtHost.Text + "_ContainerTcmId", item.TcmId);

            List<ItemInfo> list = new List<ItemInfo>();
            Functions.AddPathItem(list, item);

            this.TridionObject.TcmIdPath = list.Select(x => x.TcmId).ToList();
            
            Functions.SaveToIsolatedStorage(this.txtHost.Text + "_ContainerTcmIdPath", String.Join(";", this.TridionObject.TcmIdPath));

            list.Reverse();
            this.TridionObject.NamedPath = string.Join("/", list.Select(x => x.Title));

            this.spButtons.Visibility = Visibility.Visible;
        }

        private void treeTridionObject_OnMouseDoubleClick(object sender, MouseButtonEventArgs e)
        {
            ItemInfo item = this.treeTridionObject.SelectedItem as ItemInfo;
            if (item == null)
                return;

            if (item.ItemType == ItemType.Folder)
            {
                Process.Start(string.Format("http://{0}/SDL/#app=wcm&entry=cme&url=%23locationId%3Dtcm%3A{1}", this.txtHost.Text, item.TcmId.Replace("tcm:", "")));
            }
            else
            {
                Process.Start(string.Format("http://{0}/WebUI/item.aspx?tcm={1}#id={2}", this.txtHost.Text, (int)item.ItemType, item.TcmId));
            }
        }

        private void btnCheck_Click(object sender, RoutedEventArgs e)
        {
            if (!Functions.ExistsItem(this.txtHost.Text, this.txtUsername.Text, this.txtPassword.Password, this.TridionObject.TcmId))
                return;
            
            List<ResultInfo> results = Functions.CheckBrokenComponentsAndMetadata(this.txtHost.Text, this.txtUsername.Text, this.txtPassword.Password, this.TridionObject.TcmId);

            //show results
            ResultsWindow dialog = new ResultsWindow();
            dialog.ListBoxReport.ItemsSource = results;
            dialog.ListBoxReport.MouseDoubleClick += lbReport_OnMouseDoubleClick;
            dialog.Show();
        }

        private void btnOk_Click(object sender, RoutedEventArgs e)
        {
            this.Close();
        }

        private void lbReport_OnMouseDoubleClick(object sender, MouseButtonEventArgs e)
        {
            ListBox listBox = sender as ListBox;
            if (listBox == null)
                return;

            ResultInfo item = listBox.SelectedItem as ResultInfo;
            if (item == null)
                return;

            Process.Start(string.Format("http://{0}/WebUI/item.aspx?tcm={1}#id={2}", this.txtHost.Text, (int)item.ItemType, item.TcmId));
        }

    }
}